/*
 * Copyright 2018-12 pi-top
 *
 * atmosphere服务类
 */

package com.webide.atmosphere;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.atmosphere.config.managed.Decoder;
import org.atmosphere.config.managed.Encoder;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.Get;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


@ManagedService(path = "/chat")
public class ChatService {

    private final Logger logger = LoggerFactory.getLogger(ChatService.class);

    /**
     * 连接
     * @param resource
     */
    @Get
    public void onOpen(final AtmosphereResource resource) {
        this.logger.info("Connected" + resource.uuid(), resource.uuid());
    }

//    @Ready
//    public void onReady(final AtmosphereResource resource) {
//        this.logger.info("Connected" + resource.uuid(), resource.uuid());
//    }

    /**
     * 断开连接
     * @param event
     */
    @Disconnect
    public void onDisconnect(AtmosphereResourceEvent event) {
        this.logger.info("Client {} disconnected [{}]", event.getResource().uuid(),
                (event.isCancelled() ? "cancelled" : "closed"));
    }

    /**
     * 通讯：接收和返回信息
     * @param message
     * @return
     * @throws IOException
     */
    @org.atmosphere.config.service.Message(encoders = JacksonEncoderDecoder.class, decoders = JacksonEncoderDecoder.class)
    public Message onMessage(Message message) throws IOException {
        //this.logger.info("Client", event.getResource().uuid());
        this.logger.info("Author {} sent message {}", message.getAuthor(),
                message.getMessage());
        return message;
    }


    public static class JacksonEncoderDecoder implements Encoder<Message, String>, Decoder<String, Message> {
        private final ObjectMapper mapper = new ObjectMapper();

        /**
         * 编码
         * @param m 编码对象
         * @return  String
         */
        @Override
        public String encode(Message m) {
            try {
                return this.mapper.writeValueAsString(m);
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        }

        /**
         * 解码
         * @param s 解码字符串
         * @return  Message
         */
        @Override
        public Message decode(String s) {
            try {
                return this.mapper.readValue(s, Message.class);
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        }

    }

}
